package com.bjpowernode.springboot.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@SuppressWarnings("all")
@WebFilter("/CharacterFilter")
public class CharacterFilter implements Filter {

    public String getCharSet() {
        return charSet;
    }

    public void setCharSet(String charSet) {
        this.charSet = charSet;
    }

    private String charSet; // 创建字符集

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("++++++++++++++进入到过滤器+++++++++++++");
        String filterName = filterConfig.getFilterName(); // 获取默认字符集
        if (!filterName.equals("UTF-8")) {
            charSet = "UTF-8";
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("+++++++++++++++执行过滤器++++++++++++++");
        // 设置字符集编码
        request.setCharacterEncoding(getCharSet());
        response.setContentType("text/html;charset=utf-8");
        chain.doFilter(request,response); // 过滤
    }

    @Override
    public void destroy() {
        System.out.println("+++++++++++++++销毁过滤器++++++++++++++");
        charSet = null; // 置空字符集属性即可
    }
}
